package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("report")
public class ReportController {

    @DubboReference
    private MemberService memberService;
    @DubboReference
    private OrderService orderService;
    @DubboReference
    private ReportService reportService;

    /**
     * @Author: 15041
     * @Date: 12:00 2021/1/16
     * @Parms: []
     * @ReturnType: com.itheima.health.entity.Result
     * Description: 根据月份 折线图统计数量
     */
    @GetMapping("getMemberReport")
    public Result memberReport() {

        //根据返回值要求创建 月份集合
        List<String> months = new ArrayList<>();
        //根据返回值要求 创建总计集合
        List<Integer> memberCount = null;
        //构造months
        Calendar calendar = Calendar.getInstance();
        //回退12个月
        calendar.add(Calendar.MONTH, -12);
        DateFormat df = new SimpleDateFormat("yyyy.MM");
        //遍历获取日期
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            months.add(df.format(calendar.getTime()));
        }
        //构造memberCount 调用统计方法 将月份传入
        memberCount = memberService.countByMonth(months);
        //根据返回值需求创建map集合 封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    /**
     * @Author: 15041
     * @Date: 12:02 2021/1/16
     * @Parms: []
     * @ReturnType: com.itheima.health.entity.Result
     * Description: 套餐预约数 饼形图占比统计
     */
    @GetMapping("getSetmealReport")
    public Result getSetmealReport() {

        List<String> setmealNames = new ArrayList<>();
        List<Map<String, Object>> setmealCount = orderService.setmealByCount();
        for (Map<String, Object> map : setmealCount) {
            setmealNames.add(String.valueOf(map.get("name")));
        }
        log.info("套餐预约数-饼形图占比统计结果：{}", setmealCount);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("setmealNames", setmealNames);
        map.put("setmealCount", setmealCount);

        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    /**
     * @Author: 15041
     * @Date: 19:45 2021/1/16
     * @Parms: []
     * @ReturnType: com.itheima.health.entity.Result
     * Description: 获取运营统计数据
     * map数据格式
     * reportDate -> yyyy-MM-dd        //日期
     * todayNewMember -> number		// 今日新增会员
     * thisWeekNewMember -> number		// 本周新增会员
     * thisMonthNewMember -> number	// 本月新增会员
     * totalMember -> number			//  总会员
     * todayOrderNumber -> number		// 今日预约人数
     * thisWeekOrderNumber -> number	// 本周预约人数
     * thisMonthOrderNumber -> number	// 本月预约人数
     * todayVisitsNumber -> number		// 今日到诊人数
     * thisWeekVisitsNumber -> number	// 本周到诊人数
     * thisMonthVisitsNumber -> number	// 本月到诊人数
     * hotSetmeal ->  [ {"proportion":0.4545,"name":"粉红珍爱(女)升级TM12项筛查体检套餐","setmeal_count":5}]	// 热门套餐
     */
    @GetMapping("getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String, Object> map = reportService.getBussinessReport();
        log.info("获取运营统计数据-结果：{}", map);
        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    @GetMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) {

        //获取数据
        Map<String, Object> reportData = reportService.getBussinessReport();
        log.info("运行数据报表：{}", reportData);
        //取出返回结果
        // 取出返回结果
        String reportDate = (String) reportData.get("reportDate");
        // 获取会员相关数据
        Long todayNewMember = (Long) reportData.get("todayNewMember");
        Long thisWeekNewMember = (Long) reportData.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) reportData.get("thisMonthNewMember");
        Long totalMember = (Long) reportData.get("totalMember");
        // 获取预约相关数据
        Long todayOrderNumber = (Long) reportData.get("todayOrderNumber");
        Long thisWeekOrderNumber = (Long) reportData.get("thisWeekOrderNumber");
        Long thisMonthOrderNumber = (Long) reportData.get("thisMonthOrderNumber");
        // 获取到诊相关数据
        Long todayVisitsNumber = (Long) reportData.get("todayVisitsNumber");
        Long thisWeekVisitsNumber = (Long) reportData.get("thisWeekVisitsNumber");
        Long thisMonthVisitsNumber = (Long) reportData.get("thisMonthVisitsNumber");
        // 获取套餐数据
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");
//2-读取模板构造workBook
        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
             Workbook workbook = new XSSFWorkbook(is);
             OutputStream os = response.getOutputStream()) {
            Sheet sheet = workbook.getSheetAt(0);
            //3-填入数据
            //日期
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            //会员统计数据
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //预约到诊数据统计
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            //热门套餐
            int rowNum = 12;
            for (Map setMeal : hotSetmeal) {
                Row row = sheet.getRow(rowNum);
                row.getCell(4).setCellValue((String) setMeal.get("name"));
                row.getCell(5).setCellValue((Long) setMeal.get("setmeal_count"));
                row.getCell(6).setCellValue(((BigDecimal) setMeal.get("proportion")).doubleValue());
                rowNum++;
            }

            //4-写入网络输出流
            //写入返回流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;fileName=" + reportDate + "_report.xlsx");
            workbook.write(os);

            return null;
        } catch (IOException e) {
            log.error("", e);
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
}
